package com.jsnkj.basic.activity

import android.app.Activity
import android.content.Intent
import android.net.http.SslError
import android.os.Build
import android.os.Bundle
import android.util.Log
import android.view.KeyEvent
import android.webkit.ConsoleMessage
import android.webkit.CookieManager
import android.webkit.JsResult
import android.webkit.SslErrorHandler
import android.webkit.WebChromeClient
import android.webkit.WebResourceRequest
import android.webkit.WebSettings
import android.webkit.WebView
import android.webkit.WebViewClient
import android.widget.Toast
import com.jsnkj.basic.mvvm.BaseMVVMActivity
import com.jsnkj.basic.R
import com.jsnkj.basic.databinding.ActivityWebViewBinding
import com.jsnkj.basic.mvvm.HttpViewModel

class WebViewActivity : BaseMVVMActivity<ActivityWebViewBinding, HttpViewModel>() {
    override val layoutId: Int
        get() = R.layout.activity_web_view

    companion object {
        fun startWebActivity(activity: Activity, title: String, httpUrl: String) {
            val intent = Intent(activity, WebViewActivity::class.java)
            intent.putExtra("title", title)
            intent.putExtra("httpUrl", httpUrl)
            activity.startActivity(intent)
        }
    }

    private var webTitle = ""
    private var httpUrl = ""

    override fun initView(savedInstanceState: Bundle?) {

        webTitle = intent.getStringExtra("title") ?: ""
        httpUrl = intent.getStringExtra("httpUrl") ?: ""
        if (httpUrl.isNullOrEmpty()) {
            com.jsnkj.basic.util.ToastUtils.show("网址为空")
            onBackPressed()
            return
        }

        mVDB.topTitle.txtTopTitle.text = webTitle
        mVDB.topTitle.imageReturn.setOnClickListener {
            if (mVDB.webView.canGoBack()) {
                mVDB.webView.goBack()//返回上个页面
            } else {
                onBackPressed()
            }
        }

        com.jsnkj.basic.util.LogUtils.e("网络地址： httpUlr ==================== = $httpUrl")

        webInit()
    }

    private fun webInit() {
        mVDB.webView.settings.blockNetworkImage = false//解决图片不显示
        mVDB.webView.settings.javaScriptEnabled = true//解决图片不显示
        mVDB.webView.settings.domStorageEnabled = true
        mVDB.webView.settings.databaseEnabled = true
        mVDB.webView.settings.useWideViewPort = true
        mVDB.webView.settings.loadWithOverviewMode = true
        mVDB.webView.settings.cacheMode = WebSettings.LOAD_NO_CACHE
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            mVDB.webView.settings.mixedContentMode = WebSettings.MIXED_CONTENT_ALWAYS_ALLOW
        }

        //通过设置WebView.getSettings().setSavePassword(false)关闭webview组件的保存密码功能
        mVDB.webView.settings.savePassword = false

        mVDB.webView.settings.allowFileAccess = false

        //js通过window.androidObject.androidMethod()就可以直接调用安卓的androidMethod方法
        mVDB.webView.addJavascriptInterface(this, "android")

        com.jsnkj.basic.util.LogUtils.e("网络地址： httpUlr = $httpUrl")
        mVDB.webView.loadUrl(httpUrl)

        mVDB.webView.webChromeClient = object : WebChromeClient() {
            override fun onReceivedTitle(view: WebView, title: String) {
                super.onReceivedTitle(view, title)
            }

            override fun onConsoleMessage(consoleMessage: ConsoleMessage?): Boolean {
                Log.e(javaClass.simpleName, consoleMessage?.message().toString())
                return true
            }

            override fun onJsAlert(
                view: WebView?, url: String?,
                message: String?, result: JsResult?
            ): Boolean {
                Toast.makeText(this@WebViewActivity, message, Toast.LENGTH_SHORT).show()
                return true
            }
        }
        mVDB.webView.webViewClient = MyWebViewClient()

        mVDB.webView.requestFocus()

        if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.LOLLIPOP) {
            CookieManager.getInstance().setAcceptCookie(true)
            CookieManager.getInstance().setAcceptThirdPartyCookies(mVDB.webView, true)
        }
    }

    private inner class MyWebViewClient : WebViewClient() {

        override fun onPageFinished(view: WebView, url: String) {
            super.onPageFinished(view, url)
            com.jsnkj.basic.util.LogUtils.e("JS修改方法名", "onPageFinished 标题 == ${view.title}")
        }

        override fun shouldOverrideUrlLoading(
            view: WebView?,
            request: WebResourceRequest?
        ): Boolean {
            view?.loadUrl(httpUrl)
            com.jsnkj.basic.util.LogUtils.e("shouldOverrideUrlLoading  request == ${request?.url}")
            return super.shouldOverrideUrlLoading(view, request)
        }

        override fun onReceivedSslError(
            view: WebView?, handler: SslErrorHandler?, error: SslError?
        ) {
            com.jsnkj.basic.util.LogUtils.e("onReceivedSslError sslErrorHandler = [" + handler + "], sslError = [" + error + "]")
            super.onReceivedSslError(view, handler, error)
            handler?.proceed()
        }

    }

    /**
     * 物理按键返回
     * @param keyCode
     * @param event
     * @return
     */
    override fun onKeyDown(keyCode: Int, event: KeyEvent): Boolean {
        if (keyCode == KeyEvent.KEYCODE_BACK && mVDB.webView.canGoBack()) {
            mVDB.webView.goBack()//返回上个页面
            return true
        }
        return super.onKeyDown(keyCode, event)//退出H5界面
    }

    override fun onBackPressed() {
        if (mVDB.webView.canGoBack()) {
            mVDB.webView.goBack()//返回上个页面
        } else {
            super.onBackPressed()
        }
    }
}